<?php

namespace App\Http\Controllers;

use App\Models\AdminUser;
use App\Models\AfterSales;
use App\Models\CaseDescribe;
use App\Models\Course;
use App\Models\Doctor;
use App\Models\DoctorWorks;
use App\Models\FinancialStatementsLog;
use App\Models\Order;
use App\Models\OrderGoods;
use App\Models\ProductGoods;
use App\Models\Store;
use App\Models\StoreOrder;
use App\Util\Tool;
use App\Util\Url;
use Illuminate\Config;
use Illuminate\Http\Request;
use App\Http\Controllers\BaseController;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use WeChatPay\Builder;
use WeChatPay\Crypto\Rsa;
use WeChatPay\Util\PemUtil;
use WeChatPay\Crypto\AesGcm;
use WeChatPay\Formatter;


/***
 * Class WxPayController
 * @package App\Http\Controllers
 *
 * 微信支付
 */
class WxPayController extends BaseController
{
    /**
     * 微信支付
     */
    private static function pay($data)
    {
        // 商户号
        $merchantId = config("omnipay.wechat_pay.mch_id");
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file://' . config("omnipay.wechat_pay.merchantPrivateKeyFilePath");
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = config("omnipay.wechat_pay.m_c_serial");
        // 从本地文件中加载「微信支付平台证书」(可使用证书下载工具得到），用来验证微信支付应答的签名
        $platformCertificateFilePath = 'file://' . config("omnipay.wechat_pay.platformCertificateFilePath");
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid' => $merchantId,
            'serial' => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs' => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        // 以 Native 支付为例，发送请求
        $resp = $instance
            ->chain('v3/pay/transactions/app')
            ->post(['json' => [
                'mchid' => $merchantId,
                'out_trade_no' => $data['sn'],
                'appid' => config("omnipay.wechat_pay.app_id"),
                'description' => "益鹿出院-订单支付",
                'attach' => $data['des'],
                'notify_url' => Url::getHttpHost() . 'api/wxchat/notify',
                'amount' => [
                    'total' => $data['price'] * 100,
                    'currency' => 'CNY'
                ],
            ]]);
        $prepay_id_json = $resp->getBody();
        $resd = json_decode($prepay_id_json, true);
        $params = [
            'appId' => config("omnipay.wechat_pay.app_id"),
            'timeStamp' => (string)Formatter::timestamp(),
            'nonceStr' => Formatter::nonce(),
            'prepayid' => $resd['prepay_id'],
        ];
        $params += ['paySign' => Rsa::sign(
            Formatter::joinedByLineFeed(...array_values($params)),
            $merchantPrivateKeyInstance
        ), 'signType' => 'RSA'];
        $params['partnerId'] = $merchantId;
        $params['package'] = 'Sign=WXPay';
        return $params;
    }

    /**
     * @param $data
     * 退款
     */
    private static function refunds($data)
    {
        // 商户号
        $merchantId = config("omnipay.wechat_pay.mch_id");
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file://' . config("omnipay.wechat_pay.merchantPrivateKeyFilePath");
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = config("omnipay.wechat_pay.m_c_serial");
        // 从本地文件中加载「微信支付平台证书」(可使用证书下载工具得到），用来验证微信支付应答的签名
        $platformCertificateFilePath = 'file://' . config("omnipay.wechat_pay.platformCertificateFilePath");
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid' => $merchantId,
            'serial' => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs' => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        $url = new Url();
        $promise = $instance
            ->chain('v3/refund/domestic/refunds')
            ->postAsync([
                'json' => [
//                    'transaction_id' => '1217752501201407033233368018',
                    'out_trade_no' => $data['sn'],
                    'out_refund_no' => $data['return_sn'],
                    'amount' => [
                        'refund' => $data['price'] * 100,
                        'total' => $data['price'] * 100,
                        'currency' => 'CNY',
                    ],
                    'notify_url' => $url::getHttpHost() . 'api/wxchat/notify'
                ],
            ])->then(static function ($response) {
                // 正常逻辑回调处理
//                echo $response->getBody(), PHP_EOL;
                return json_decode($response->getBody(), true);
            })->otherwise(static function ($e) {
                // 异常错误处理
//                echo $e->getMessage(), PHP_EOL;
                if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                    $r = $e->getResponse();
//                    echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
//                    echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
                    return json_decode($r->getBody(), true);
                }
//                echo $e->getTraceAsString(), PHP_EOL;
            });;

        // 同步等待
        $res = $promise->wait();
        return $res;
        $promise->wait();

        // 正常逻辑回调处理
        $jsonRes = $dats->getBody();
        $dataRes = json_decode($jsonRes, true);
        if ($dataRes['status'] == 'SUCCESS') {
            return true;
        } elseif ($dataRes['status'] == 'PROCESSING') {
            return "退款处理中";
        } elseif ($dataRes['status'] == 'ABNORMAL') {
            return "退款异常";
        } elseif ($dataRes['status'] == 'CLOSED') {
            return "退款关闭";
        } else {
            return $dataRes;
        }
    }


    /**
     *查询订单
     */
    private function orderDetail($data)
    {
        // 商户号
        $merchantId = config("omnipay.wechat_pay.mch_id");
        // 从本地文件中加载「商户API私钥」，「商户API私钥」会用来生成请求的签名
        $merchantPrivateKeyFilePath = 'file://' . config("omnipay.wechat_pay.merchantPrivateKeyFilePath");
        $merchantPrivateKeyInstance = Rsa::from($merchantPrivateKeyFilePath, Rsa::KEY_TYPE_PRIVATE);
        // 「商户API证书」的「证书序列号」
        $merchantCertificateSerial = config("omnipay.wechat_pay.m_c_serial");
        // 从本地文件中加载「微信支付平台证书」(可使用证书下载工具得到），用来验证微信支付应答的签名
        $platformCertificateFilePath = 'file://' . config("omnipay.wechat_pay.platformCertificateFilePath");
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);
        // 从「微信支付平台证书」中获取「证书序列号」
        $platformCertificateSerial = PemUtil::parseCertificateSerialNo($platformCertificateFilePath);
        // 构造一个 APIv3 客户端实例
        $instance = Builder::factory([
            'mchid' => $merchantId,
            'serial' => $merchantCertificateSerial,
            'privateKey' => $merchantPrivateKeyInstance,
            'certs' => [
                $platformCertificateSerial => $platformPublicKeyInstance,
            ],
        ]);
        $promise = $instance
            ->v3->pay->transactions->outTradeNo->_out_trade_no_
            ->getAsync([
                // 请求消息
                'query' => ['mchid' => $merchantId],
                // 变量名 => 变量值
                'out_trade_no' => $data['sn'],
            ])->then(static function ($response) {
                // 正常逻辑回调处理
                return json_decode($response->getBody(), true);
            })
            ->otherwise(static function ($e) {
                // 异常错误处理
//                echo $e->getMessage(), PHP_EOL;
                if ($e instanceof \GuzzleHttp\Exception\RequestException && $e->hasResponse()) {
                    $r = $e->getResponse();
                    return json_decode($r->getBody(), true);
//                    echo $r->getStatusCode() . ' ' . $r->getReasonPhrase(), PHP_EOL;
//                    echo $r->getBody(), PHP_EOL, PHP_EOL, PHP_EOL;
                }
//                echo $e->getTraceAsString(), PHP_EOL;
            });;
        // 同步等待
        $res = $promise->wait();
        return $res;
    }


    /**
     * 申请支付
     */
    public static function setPay($data)
    {
        $res = self::pay($data);
        return $res;
    }

    public function returnBack($data)
    {
//        $data['sn'] = "2024053148995357";
//        $data['return_sn'] = "20240531148995357";
//        $data['price'] = "1";
        $detail = self::orderDetail($data);
//       dd($detail);
        if (isset($detail['trade_state']) && $detail['trade_state'] == 'REFUND') {
            return "refund";
        }
        $res = self::refunds($data);
        if (isset($res['status']) && $res['status']  == "SUCCESS") {
            return true;
        } else {
            return $res;
        }
    }


    public function testBack(Request $request)
    {
        $order = (new Order())->where([['pay_status', '=', 1]])->get();
        $oids = [];
        foreach ($order as $k => $v) {
            $data['sn'] = $v->sn;
            $data['price'] = $v->pay_price;
            $data['return_sn'] = (new Order())->orderNumber();
            $detail = self::orderDetail($data);
            if (isset($detail['trade_state']) && $detail['trade_state'] == 'REFUND') {
                continue;
            }
            $res = self::refunds($data);
            if ($res) {
                $oids[] = $v->id;
            }
        }
        $store = (new StoreOrder())->where([['pay_status','=',1]])->get();
        $sto = [];
        foreach ($store as $k => $v) {
            $data['sn'] = $v->sn;
            $data['price'] = $v->money;
            $data['return_sn'] = (new Order())->orderNumber();
            $detail = self::orderDetail($data);
            if (isset($detail['trade_state']) && $detail['trade_state'] == 'REFUND') {
                continue;
            }
            $res = self::refunds($data);
            if ($res) {
                $sto[] = $v->id;
            }
        }
        dd(array_merge($oids,$sto));
    }

    public function notify(Request $request)
    {
        $head = $request->header();
        $inBody = $request->getContent();
        $inWechatpaySignature = $head['wechatpay-signature'];// 请根据实际情况获取
        $inWechatpayTimestamp = $head['wechatpay-timestamp'];// 请根据实际情况获取
        $inWechatpaySerial = $head['wechatpay-serial'];// 请根据实际情况获取
        $inWechatpayNonce = $head['wechatpay-nonce'];// 请根据实际情况获取
        $inBodyArray_log = (array)json_decode($inBody, true);
        $apiv3Key = config("omnipay.wechat_pay.mch_key");// 在商户平台上设置的APIv3密钥

// 根据通知的平台证书序列号，查询本地平台证书文件，
// 假定为 `/path/to/wechatpay/inWechatpaySerial.pem`
        $platformCertificateFilePath = 'file://' . config("omnipay.wechat_pay.platformCertificateFilePath");
        $platformPublicKeyInstance = Rsa::from($platformCertificateFilePath, Rsa::KEY_TYPE_PUBLIC);

// 检查通知时间偏移量，允许5分钟之内的偏移
        $timeOffsetStatus = 300 <= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
//        $verifiedStatus = Rsa::verify(
//        // 构造验签名串
//            Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
//            $inWechatpaySignature,
//            $platformPublicKeyInstance
//        );
//        $this->writeLog(['11111111'=>$verifiedStatus]);
//        dd($verifiedStatus);
//        if ($timeOffsetStatus && $verifiedStatus) {
        if ($timeOffsetStatus) {
            // 转换通知的JSON文本消息为PHP Array数组
            $inBodyArray = (array)json_decode($inBody, true);
            $this->writeLog(['start' => '333333333333333333333333']);
            $this->writeLog($inBodyArray);
            $this->writeLog(['end' => '44444444444444444444444444444']);
            // 使用PHP7的数据解构语法，从Array中解构并赋值变量
            ['resource' => [
                'ciphertext' => $ciphertext,
                'nonce' => $nonce,
                'associated_data' => $aad
            ]] = $inBodyArray;
            // 加密文本消息解密
            $inBodyResource = AesGcm::decrypt($ciphertext, $apiv3Key, $nonce, $aad);
            // 把解密后的文本转换为PHP Array数组
            $inBodyResourceArray = (array)json_decode($inBodyResource, true);
            $this->writeLog(['start' => '1111111111111111111111111']);
            $this->writeLog($inBodyResourceArray);
            $this->writeLog(['前end' => '2222222222222222222222222222222']);
            if (isset($inBodyResourceArray['trade_state']) && ($inBodyResourceArray['trade_state'] == "SUCCESS")) { //支付回调
                $statement = new PaymentController();
                $arr = explode('_', trim($inBodyResourceArray['attach']));
                if (isset($arr[0]) && ($arr[0] == '100')) { //商圈支付回调
                    $store_order = new StoreOrder();
                    $info_store_order = $store_order->where([['sn', '=', $inBodyResourceArray['out_trade_no']]])->first();
                    if ($info_store_order->pay_status == 1) {
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        die;
                    }
                    $lit['order_status'] = 1;
                    $lit['pay_status'] = 1;
                    $lit['pay_time'] = date("Y-m-d H:i:s", time());
                    $store_order->where([['sn', '=', $inBodyResourceArray['out_trade_no']]])->update($lit);
                    (new Store())->where([['id', '=', $info_store_order->store_id]])->update(['topping' => $info_store_order->type, 'buy_type' => $info_store_order->type_id, "is_online" => 1]);
                    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    die;
                } else {
                    // 处理支付成功的情况
                    // 根据返回的订单号查询订单数据
                    $order = (new Order())->where([['sn', '=', $inBodyResourceArray['out_trade_no']]])->first();
                    $order_goods = (new OrderGoods())->where([['order_id', '=', $order->id]])->first();
                    if (empty($order)) {
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
                        die;
                    }
                    if ($order->pay_status == 1) {
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        die;
                    }
                    try {
                        DB::beginTransaction(); // 开始事务
                        $list['pay_time'] = date("Y-m-d H:i:s:", time());
                        $list['pay_status'] = 1;
                        if ($order->order_type == 1) {  //课程
                            $list['delivery_time'] = date("Y-m-d H:i:s:", time());
                            $list['delivery_status'] = 1;
                            $list['receive_time'] = date("Y-m-d H:i:s:", time());
                            $list['receive_status'] = 1;
                            $list['order_status'] = 1;
                            //增加销量
                            (new Course())->where([['id', '=', $order_goods->goods_id]])->increment("buy_num", $order->goods_num);
                            //添加账单记录
                            $statement->addStatements($order, $order_goods);
                        } else if ($order->order_type == 2) {  //商品
                            //增加销量
                            (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->increment("product_sales", $order->goods_num);
                            //减少库存
                            (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->decrement("product_stock", $order->goods_num);
                            //添加账单记录
                            $statement->addStatements($order, $order_goods);
                        } else if ($order->order_type == 3 || $order->order_type == 4) {  //图文和电话
                            //增加销量
                            (new Doctor())->where([['id', '=', $order_goods->goods_id]])->increment("consult_num", 1);
                            //添加账单记录
                            $statement->addStatements($order, $order_goods);
                        }
                        (new Order())->where([['id', '=', $order->id]])->update($list);
                        DB::commit(); // 提交事务
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        die;
                    } catch (Exception $e) {
                        DB::rollback(); // 回滚事务
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
                        die;
                    }
                }
            } elseif (isset($inBodyResourceArray['refund_status']) && ($inBodyResourceArray['refund_status'] == "SUCCESS")) { //退款回调
                $this->writeLog(['testback' => '***************************************************5555555555555555555555555888888888888888888888']);
                $this->writeLog(['body' => $inBodyResourceArray]);
                $order = new Order();
                $order_goods = new OrderGoods();
                $goods = new ProductGoods();
                $financialStatementsLog = new FinancialStatementsLog();
                $orderInfo = $order->where([['sn', '=', $inBodyResourceArray['out_trade_no']]])->first();
                $orderGoods = $order_goods->where([['order_id', '=', $orderInfo->id]])->first();
                if($orderInfo->order_status == 3 || $orderInfo->order_status == 4){   //订单已完成
                    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    die;
                }
                if ($orderInfo->order_type == 1) { //课程

                } elseif ($orderInfo->order_type == 2) { //商品
                    if ($orderInfo->pay_status == 1 && $orderInfo->delivery_status == 0) { //付款后7天未发货或者取消订单
                        $financialStatementsLog->setGoodsOrderBack($orderInfo->id);
                        //取消订单
                        $order->where([['id', '=', $orderInfo->id]])->update(['order_status' => 4]);
                        //增加库存销量
                        $o_goods = $order_goods->where([['order_id', '=', $orderInfo->id]])->first();
                        $goods->where([['id', '=', $o_goods->goods_id]])->increment("product_stock", $o_goods->goods_num);//加库存
                        $goods->where([['id', '=', $o_goods->goods_id]])->decrement("product_sales", 1);//减销量
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        die;
                    } else if ($orderInfo->order_status == 2) { //售后订单
//                        $this->writeLog(['售后订单开始' => $orderInfo->sn]);
                        $this->writeLog(['aftersale_start' => $orderInfo->id]);
                        $after_info = (new AfterSales())->where([['order_id', '=', $orderInfo->id]])->first();
                        //退回账单记录
                        $financialStatementsLog->setAfterAgreeGoodsOrderBack($orderInfo->id);
                        $o_goods = $order_goods->where([['order_id', '=', $orderInfo->id]])->first();
                        $goods->where([['id', '=', $o_goods->goods_id]])->increment("product_stock", $o_goods->goods_num);//加库存
                        $goods->where([['id', '=', $o_goods->goods_id]])->decrement("product_sales", 1);//减销量
                        //修改订单
                        $lit['order_status'] = 3;
                        $sh = $order->where([['id', '=', $orderInfo->id]])->update($lit);
                        $this->writeLog(['update_order_status' => $sh]);
                        //修改售后订单
                        $after_info->after_status = 1;
                        $after_info->status = 1;
                        $sh_sta = $after_info->save();
                        $this->writeLog(['update_sale_order_status' => $sh_sta]);
                        echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                        die;
                    }
                } elseif ($orderInfo->order_type == 3 || $orderInfo->order_type == 4) { //3图文4电话
//                    if($orderInfo->pay_status ==1 && $orderInfo->delivery_status == 0){ //咨询时间到未接单
                    $financialStatementsLog::setBackConsultOrder($orderInfo, $orderGoods);
                    $order->where([['id', '=', $orderInfo->id]])->update(['order_status' => 4]);
//                    }elseif ($orderInfo->delivery_status == 1 && $orderInfo->receive_status == 0){
//                        $financialStatementsLog::setBackConsultOrder($orderInfo,$orderGoods);
//                        $order->where([['id','=',$orderInfo->id]])->update(['order_status'=>4]);
//                    }
                    echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
                    die;
                }
            } else {
                echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
                die;
            }
        } else {
            echo '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[FAIL]]></return_msg></xml>';
            die;
        }
    }


    /**
     * 写入删除log
     */
    public function writeLog($data)
    {
        $filepath = base_path() . "/storage/logs/wechat/";
        if (!is_dir($filepath)) {
            mkdir($filepath);
        }
        $filename = "del_log" . date("Ymd") . ".txt";
        $file = $filepath . $filename;
        if (is_file($file)) {
            chmod($file, 0777);
            $fh = fopen($file, "a+");
        } else {
            $fh = fopen($file, "a+");
            chmod($file, 0777);
        }
        $content = json_encode($data);
        if ($fh) {
            fwrite($fh, date("Y-m-d H:i:s") . ": $content \r\n");
        }
        fclose($fh);
    }


    /**
     * @param $order
     * @param $order_goods
     * @return bool
     * 添加账单
     * 价格待处理
     */
    public function addStatements($order, $order_goods)
    {
        $data['sn'] = $order->sn;
        $data['date_str'] = date("Y-m-d H:i:s", time());
        $data['goods_num'] = $order->goods_num;
        $data['names'] = $order_goods->goods_name;
        $data['work_id'] = $order->work_id;
        $data['goods_id'] = $order_goods->goods_id;
        $data['order_id'] = $order->id;
        $data['updated_at'] = date("Y-m-d H:i:s", time());
        $data['created_at'] = date("Y-m-d H:i:s", time());
        if ($order->order_type == 1) {  //课程
            $data['type'] = 1;
            $data['settle_status'] = 1;
            $data['add_or_sub'] = 1;
            $data['divide_type'] = 1;
            $course = (new Course())->where([['id', '=', $order_goods->goods_id]])->first();
            //判断课程是否是自己的工作室
            if ($course->work_id == $order->work_id) {   //工作室自己的课程
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "课程收费";
                    return (new FinancialStatementsLog())->insert($data);
                }
                //工作室余额加钱
                (new DoctorWorks())
                    ->where([["id", '=', $order->work_id]])
                    ->increment("surplus", $order->self_work_price);
            } else {
                //本工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "分享课程收费";
                    return (new FinancialStatementsLog())->insert($data);
                }
                //分享工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->id], ['work_id', '=', $course->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->share_work_price;
                    $data['work_id'] = $course->work_id;
                    return (new FinancialStatementsLog())->insert($data);
                }
                //工作室加钱
                (new DoctorWorks())->where([["id", '=', $order->work_id]])->increment("surplus", $order->self_work_price);
                (new DoctorWorks())->where([["id", '=', $course->work_id]])->increment("surplus", $order->share_work_price);
            }
        } elseif ($order->order_type == 2) {   //商品
            $data['type'] = 2;
            $data['settle_status'] = 0;
            $data['add_or_sub'] = 1;
            $goods = (new ProductGoods())->where([['id', '=', $order_goods->goods_id]])->first();
            $data['divide_type'] = 1;
            if ($goods->product_source == 1) { //工作室产品
                if ($goods->supplier_work_id == $order->work_id) { //工作室自己的产品
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['money'] = $order->self_work_price;
                        $data['remarks'] = "商品收费";
                        (new FinancialStatementsLog())->insert($data);
                    }
                } else { //分享产品
                    //本工作室账单情况
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['remarks'] = "分享商品收费";
                        $data['money'] = $order->self_work_price;
                        (new FinancialStatementsLog())->insert($data);
                    }
                    //分享工作室账单情况
                    $info = (new FinancialStatementsLog())
                        ->where([['order_id', '=', $order->id], ['work_id', '=', $goods->supplier_work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                        ->first();
                    if (empty($info)) {
                        $data['money'] = $order->share_work_price;
                        $data['work_id'] = $goods->supplier_work_id;
                        (new FinancialStatementsLog())->insert($data);
                    }
                }
            } elseif ($goods->product_source == 2) {  //供应商产品
                //本工作室账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->self_work_price;
                    $data['remarks'] = "供应商商品收费";
                    (new FinancialStatementsLog())->insert($data);
                }
                //供应商账单情况
                $info = (new FinancialStatementsLog())
                    ->where([['order_id', '=', $order->id], ['work_id', '=', $goods->supplier_work_id], ['divide_type', '=', 2], ['add_or_sub', '=', 1]])
                    ->first();
                if (empty($info)) {
                    $data['money'] = $order->supplier_price;
                    $data['work_id'] = $goods->supplier_work_id;
                    $data['divide_type'] = 2;
                    $data['remarks'] = "卖出商品收费";
                    (new FinancialStatementsLog())->insert($data);
                }
            }
        } elseif ($order->order_type == 3 || $order->order_type == 4) { //图文||电话
            $case = (new CaseDescribe())->where([['id', '=', $order_goods->specs_id]])->first();
            $data['sex'] = $case->sex;
            $data['age'] = $case->age;
            $data['type'] = 3;
            $data['settle_status'] = 0;
            $data['add_or_sub'] = 1;
            $data['divide_type'] = 1;
            $info = (new FinancialStatementsLog())
                ->where([['order_id', '=', $order->id], ['work_id', '=', $order->work_id], ['divide_type', '=', 1], ['add_or_sub', '=', 1]])
                ->first();
            if (empty($info)) {
                $data['money'] = $order->self_work_price;
                $data['remarks'] = "咨询收费";
                (new FinancialStatementsLog())->insert($data);
            }
        }
        return true;
    }


    private function getNotify(Request $request = null)
    {
        $request = Request::createFromGlobals();
        Log::channel('daily')->info($request->getContent());
        try {
            $xml = XML::parse(strval($request->getContent()));
        } catch (\Throwable $e) {
            throw new Exception('Invalid request XML: ' . $e->getMessage(), 400);
        }
        if (!is_array($xml) || empty($xml)) {
            throw new Exception('Invalid request XML.', 400);
        }
        return new Collection($xml);
    }


    public function return(Request $request = null)
    {

    }
}
